import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
//请提示
import { Toast } from 'vant';

import login from '@/views/login'
import home from '@/views/home'
import ask from '@/views/ask'
import video from '@/views/video'
import my from '@/views/my'
Vue.use(VueRouter)

const routes = [
  { path: '', redirect: '/login' },
  { path: '/login', component: login },
  {
    path: '/layout', component: () => import('@/views/layout'),
    children: [
      { path: 'home', component: () => import('@/views/home') , meta: { needKeep: true}},
      { path: 'ask', component: () => import('@/views/ask') },
      { path: 'video', component: () => import('@/views/video') },
      { path: 'my', component: () => import('@/views/my'), meta: { needLogin: true } },// 判断当前路由是否需要登录
      
    ]
  },
  { path: '/my/edit', component: () => import('@/views/my/edit'),
  meta: { needLogin: true }  },
  { path: '/home/detail', component: () => import('@/views/detail')
  },
  { path: '/home/search', component: () => import('@/views/search')
  },
  { path: '/search/result', component: () => import('@/views/result')
  },
  { path: '/my/zhi', component: () => import('@/views/zhi'),
  meta: { needLogin: true }  },
]

const router = new VueRouter({
  routes
})
//导航守卫 由一个路由跳转到另一个路由时触发  首先判断当前路由是否需要登录 ， 在判断是否有token
router.beforeEach((to, from, next) => {
  const needLogin = to.meta.needLogin
  if(needLogin) {
    const token = store.state.token.token
    if(token) {
      next()
    } else {
      Toast.fail('您还没有登录')
      //保存当前访问的路劲
      next(`/login?url=${to.path}`)
      // router.push('/login')
    }
  
  } else {
    next()
  }
})

export default router
